use std::collections::HashMap;

#[derive(Debug)]
struct Person {
    name: String,
    age: u8,
    height: u8,
}

fn base_sort() {
    let mut v = Vec::new();
    v.push('a');
    v.push('a');
    println!("{:?}", v);

    let mut v = vec![8, 2, 13, 7, 8];
    println!("{:?}", v);

    v.sort_unstable();
    println!("{:?}", v);
}

fn struct_sort() {
    let mut people = vec![
        Person { name: "Alice".to_string(), age: 20, height: 178 },
        Person { name: "Bob".to_string(), age: 15, height: 167 },
        Person { name: "Charlie".to_string(), age: 10, height: 180 },
    ];

    people.sort_unstable_by(|a, b| a.age.cmp(&b.age));
    println!("{:#?}", people);

    people.sort_unstable_by(|a, b| a.height.cmp(&b.height));
    println!("{:#?}", people);
}

fn test_vec() {
    println!("\n------------ Test Vector ----------------");
    base_sort();
    struct_sort();
}

fn hashmap_new() {
    let mut scores = HashMap::new();

    scores.insert(String::from("Blue"), 10);
    scores.insert(String::from("Yellow"), 50);
    println!("{:#?}", scores);
}

fn hashmap_collect()  {
    let teams = vec![
        ("中国队".to_string(), 100),
        ("美国队".to_string(), 10),
        ("日本队".to_string(), 1),
    ];

    let teams_map: HashMap<_, _> = teams.into_iter().collect();
    println!("{:#?}", teams_map);
    println!("中国队：{}", teams_map["中国队"]);
}

fn hashmap_operation() {
    let mut scores = HashMap::new();

    // 增加元素
    scores.insert(String::from("中国队"), 100);
    scores.insert(String::from("日本队"), 1);
    scores.insert(String::from("美国队"), 10);
    println!("{:?}", scores);

    // 删除元素
    scores.remove("日本队");
    println!("{:?}", scores);

    // 修改元素
    scores.insert(String::from("中国队"), 200);
    println!("{:?}", scores);

    // 查找元素
    if let Some(&score) = scores.get("中国队") {
        println!("中国队：{}", score);
    }

    if let Some(&score) = scores.get("日本队") {
        println!("日本队：{}", score);
    } else {
        println!("日本队：未找到");
    }

    let score : Option<&i32> = scores.get("美国队");
    println!("美国队：{:?}", score);

    // 遍历元素
    for (key, value) in &scores {
        println!("{}: {}", key, value);
    }
}

fn test_hashmap() {
    println!("\n------------ Test Hashmap ---------------");
    hashmap_new();
    hashmap_collect();
    hashmap_operation();
}

fn main() {
    test_vec();
    test_hashmap();
}
